//
//  VideoPlayerViewController.m
//  TYVideoPlayerDemo
//
//  Created by tany on 16/7/11.
//  Copyright © 2016年 tany. All rights reserved.
//

#import "VideoPlayerViewController.h"
#import "TYVideoPlayerController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "AppDelegate.h"

@interface VideoPlayerViewController ()<TYVideoPlayerControllerDelegate>
@property (nonatomic, weak) TYVideoPlayerController *playerController;

@property (nonatomic, strong)UIAlertView *alertV;

@property (nonatomic, assign) BOOL cwq_isPlayed;
//当前的网路状态
@property (nonatomic, assign)AFNetworkReachabilityStatus status;

//开始时间
@property (nonatomic, strong)NSDate *startDate;
//结束时间
@property (nonatomic, strong)NSDate *endDate;

@end

@implementation VideoPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (!_videlUrl) {
        
        _videlUrl = [NSURL URLWithString:@"http://baobab.wdjcdn.com/1442142801331138639111.mp4"];
    }
    [self addVideoPlayerController];
    
    _cwq_isPlayed = NO;
    weakSelf_define;
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [weakSelf cwq_mornitorNetwork:status];
    }];

    
//    [self loadVodVideo];
}

- (void)cwq_mornitorNetwork:(AFNetworkReachabilityStatus)status {
    
    
    
    if (_cwq_isPlayed) {
        if (_status == status) {
            return;
        }
        
    }
    _status = status;
    [_alertV dismissWithClickedButtonIndex:0 animated:YES];
    if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
        //流量
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前是流量网络，是否播放？" delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否", nil];
        _alertV = alertV;
        [alertV show];
    } else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {

        //wifi
        if (_cwq_isPlayed) {
            [_playerController play];
            return;
        }
        if (_videlUrl) {
            [_playerController loadVideoWithStreamURL:_videlUrl];
            _cwq_isPlayed = YES;
        }
    } else {
        //网络不可用
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不可用，将无法播放" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertV.tag = 10010;
        _alertV = alertV;
        [alertV show];
    }
    
}



- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    _startDate = [NSDate date];
    AppDelegate  *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.is_LaunchScreen = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _endDate = [NSDate date];
    NSTimeInterval time = [_endDate timeIntervalSinceDate:_startDate];
    WSJLog(@"_______________%f秒",time);
    [super viewWillDisappear:animated];
    AppDelegate  *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.is_LaunchScreen = NO;
}

#pragma mark - ------------UIAlertViewDelegate---------------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 10010) {
        return;
    }
    
    if (buttonIndex == 0) {
        if (_cwq_isPlayed) {
            [_playerController play];
        }else {
            if (_videlUrl) {
                [_playerController loadVideoWithStreamURL:_videlUrl];
                _cwq_isPlayed = YES;
            }
        }
    }else {
        [_playerController pause];
    }
}



- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    CGRect frame = self.view.frame;
    if (_playerController.isFullScreen) {
        _playerController.view.frame = CGRectMake(0, 0, MAX(CGRectGetHeight(frame), CGRectGetWidth(frame)), MIN(CGRectGetHeight(frame), CGRectGetWidth(frame)));
    }else {
         _playerController.view.frame = CGRectMake(0, 0, MIN(CGRectGetHeight(frame), CGRectGetWidth(frame)), MIN(CGRectGetHeight(frame), CGRectGetWidth(frame))*9/16);
    }
}

- (BOOL)prefersStatusBarHidden
{
    if (!_playerController || !_playerController.isFullScreen) {
        return NO;
    }
    return [_playerController isControlViewHidden];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation )preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationFade;
}

- (void)addVideoPlayerController
{
    TYVideoPlayerController *playerController = [[TYVideoPlayerController alloc]init];
    //playerController.shouldAutoplayVideo = NO;
    playerController.delegate = self;
    [self addChildViewController:playerController];
    [self.view addSubview:playerController.view];
    _playerController = playerController;
}

- (void)loadVodVideo
{
    // 点播
    // http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8
    NSURL *streamURL = [NSURL URLWithString:@"http://baobab.wdjcdn.com/1442142801331138639111.mp4"];
    
    [_playerController loadVideoWithStreamURL:streamURL];
}

- (void)loadLiveVideo
{
    // 直播
    NSURL *streamURL = [NSURL URLWithString:@"http://live.hkstv.hk.lxdns.com/live/hks/playlist.m3u8"];
    
    [_playerController loadVideoWithStreamURL:streamURL];
}

- (void)loadLocalVideo
{
    // 本地播放
    NSString* path = [[NSBundle mainBundle] pathForResource:@"test_264" ofType:@"mp4"];
    if (!path) {
        UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"本地文件不存在！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alerView show];
        return;
    }
    NSURL* streamURL = [NSURL fileURLWithPath:path];
    [_playerController loadVideoWithStreamURL:streamURL];
}


#pragma mark - action

- (IBAction)playVodAction:(id)sender {
    [self loadVodVideo];
}

- (IBAction)playLiveAction:(id)sender {
    [self loadLiveVideo];
}

- (IBAction)playLocalAction:(id)sender {
    [self loadLocalVideo];
}

#pragma mark - delegate

- (void)videoPlayerController:(TYVideoPlayerController *)videoPlayerController readyToPlayURL:(NSURL *)streamURL
{
    
}

- (void)videoPlayerController:(TYVideoPlayerController *)videoPlayerController endToPlayURL:(NSURL *)streamURL
{
    
}

- (void)videoPlayerController:(TYVideoPlayerController *)videoPlayerController handleEvent:(TYVideoPlayerControllerEvent)event
{
    switch (event) {
        case TYVideoPlayerControllerEventTapScreen:
            [self setNeedsStatusBarAppearanceUpdate];
            break;
        default:
            break;
    }
}

#pragma mark - rotate

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    //发生在翻转开始之前
    CGRect bounds = self.view.frame;
    [UIView animateWithDuration:duration animations:^{
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
             _playerController.view.frame = CGRectMake(0, 0, MAX(CGRectGetHeight(bounds), CGRectGetWidth(bounds)), MIN(CGRectGetHeight(bounds), CGRectGetWidth(bounds)));
        }else {
             _playerController.view.frame = CGRectMake(0, 0, MIN(CGRectGetHeight(bounds), CGRectGetWidth(bounds)), MIN(CGRectGetHeight(bounds), CGRectGetWidth(bounds))*9/16);
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
